// backend/controllers/checkinController.js

const db = require('../config/db');
const moment = require('moment'); // 确保你已经安装并引入了 moment (npm install moment)


// Handle new check-in
exports.createCheckin = async (req, res) => {
    try {
        const { guest_id, room_id, checkin_date } = req.body; // 注意这里是 checkin_date 而不是 check_in_time

        const [room] = await db.query('SELECT status FROM Rooms WHERE room_id = ?', [room_id]);
        if (room.length === 0 || room[0].status !== '空闲') {
            return res.status(400).json({ error: '房间不可用', message: '该房间当前不空闲或不存在。' });
        }

        const [guest] = await db.query('SELECT guest_id FROM Guests WHERE guest_id = ?', [guest_id]);
        if (guest.length === 0) {
            return res.status(400).json({ error: '客户不存在', message: '请先添加客户信息。' });
        }

        const [existingCheckin] = await db.query(
            'SELECT * FROM Checkins WHERE guest_id = ? AND room_id = ? AND status = "入住中"',
            [guest_id, room_id]
        );
        if (existingCheckin.length > 0) {
            return res.status(400).json({ error: '重复入住', message: '该客户已入住此房间。' });
        }

        // total_amount 在入住时可以为 NULL 或 0，在退房时才计算
        const [result] = await db.query(
            'INSERT INTO Checkins (guest_id, room_id, checkin_date, status, total_amount) VALUES (?, ?, ?, "入住中", NULL)', // 将 total_amount 初始化为 NULL
            [guest_id, room_id, checkin_date] // 使用 checkin_date
        );
        await db.query('UPDATE Rooms SET status = "已入住" WHERE room_id = ?', [room_id]);

        res.status(201).json({ message: '入住办理成功', checkinId: result.insertId });
    } catch (err) {
        console.error('办理入住错误:', err);
        res.status(500).json({ error: '办理入住失败', details: err.message });
    }
};

// Handle checkout
exports.checkout = async (req, res) => {
    try {
        const { id } = req.params; // checkin_id
        const checkoutTime = req.body.check_out_time || moment().format('YYYY-MM-DD HH:mm:ss'); // 获取退房时间

        const [checkinRows] = await db.query(
            'SELECT checkin_id, room_id, checkin_date, guest_id FROM Checkins WHERE checkin_id = ? AND status = "入住中"',
            [id]
        );
        if (checkinRows.length === 0) {
            return res.status(404).json({ error: '入住记录未找到或已退房' });
        }

        const { room_id, checkin_date, guest_id } = checkinRows[0];

        // 1. 获取房间价格
        const [roomResult] = await db.query('SELECT price FROM Rooms WHERE room_id = ?', [room_id]);
        if (roomResult.length === 0) {
            return res.status(404).json({ error: '房间信息未找到' });
        }
        const roomPricePerDay = parseFloat(roomResult[0].price);

        // 2. 计算入住天数
        const checkinMoment = moment(checkin_date);
        const checkoutMoment = moment(checkoutTime);

        // 计算入住天数：如果入住和退房在同一天，算1天。否则，按跨越的自然天数计算。
        let stayDays = checkoutMoment.diff(checkinMoment, 'days');
        if (stayDays === 0 && checkinMoment.date() !== checkoutMoment.date()) {
            stayDays = 1; // 跨日但不足24小时，例如23:00入住，次日01:00退房，算作1天
        } else if (stayDays === 0 && checkinMoment.date() === checkoutMoment.date()) {
            stayDays = 1; // 同一天入住和退房，算1天
        } else {
            stayDays = stayDays + 1; // 跨多天的情况，例如27号入住，29号退房，diff是2天，实际住了3天 (27, 28, 29)
        }
        stayDays = Math.max(1, stayDays); // 确保至少为1天

        const roomStayAmount = roomPricePerDay * stayDays;

        // 3. 获取该入住记录的所有消费总额
        const [consumptionSumResult] = await db.query(
            'SELECT COALESCE(SUM(amount), 0) AS totalConsumptionAmount FROM Consumptions WHERE checkin_id = ?',
            [id]
        );
        const totalConsumptionAmount = parseFloat(consumptionSumResult[0].totalConsumptionAmount || 0); // 确保是数字且处理null

        // 4. 计算总金额
        const totalAmount = roomStayAmount + totalConsumptionAmount;

        // 5. 更新 Checkins 表，包括 checkout_date, status, total_amount
        const [result] = await db.query(
            'UPDATE Checkins SET checkout_date = ?, status = "已退房", total_amount = ? WHERE checkin_id = ?',
            [checkoutTime, totalAmount, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: '退房失败', message: '入住记录不存在或状态不正确。' });
        }

        // 6. 更新房间状态
        await db.query('UPDATE Rooms SET status = "空闲" WHERE room_id = ?', [room_id]);

        res.status(200).json({ message: '退房成功', totalAmount: totalAmount });
    } catch (err) {
        console.error('办理退房错误:', err);
        res.status(500).json({ error: '办理退房失败', details: err.message });
    }
};

// Get all check-in records (管理员界面使用，支持筛选和分页)
exports.getAllCheckins = async (req, res) => {
    try {
        const { status, room_number, guest_name, id_card, startDate, endDate, limit, offset } = req.query;
        let query = `
            SELECT
                c.checkin_id,
                r.room_number,
                g.name AS guest_name,
                g.id_card,
                r.room_type,
                r.price AS room_price,
                c.checkin_date,
                c.checkout_date,
                c.status,
                c.total_amount
            FROM Checkins c
                     JOIN Rooms r ON c.room_id = r.room_id
                     JOIN Guests g ON c.guest_id = g.guest_id
            WHERE 1=1
        `;
        const params = [];

        if (status) {
            query += ' AND c.status = ?';
            params.push(status);
        }
        if (room_number) {
            query += ' AND r.room_number LIKE ?';
            params.push(`%${room_number}%`);
        }
        if (guest_name) {
            query += ' AND g.name LIKE ?';
            params.push(`%${guest_name}%`);
        }
        if (id_card) {
            query += ' AND g.id_card LIKE ?';
            params.push(`%${id_card}%`);
        }
        if (startDate) {
            query += ' AND c.checkin_date >= ?';
            params.push(startDate);
        }
        if (endDate) {
            query += ' AND c.checkin_date <= ?';
            params.push(endDate);
        }

        // 获取总数
        const [totalCountResult] = await db.query(`SELECT COUNT(*) as total FROM (${query}) AS temp`, params);
        const total = totalCountResult[0].total;

        query += ' ORDER BY c.checkin_date DESC'; // 默认按入住时间倒序

        // 分页
        if (limit) {
            query += ' LIMIT ?';
            params.push(parseInt(limit));
        }
        if (offset) {
            query += ' OFFSET ?';
            params.push(parseInt(offset));
        }

        const [rows] = await db.query(query, params);
        res.status(200).json({
            data: rows,
            total: total
        });
    } catch (err) {
        console.error('获取所有入住记录错误:', err);
        res.status(500).json({ error: '获取入住记录失败', details: err.message });
    }
};


// Get currently active check-ins (for consumption management dropdown 或仪表盘)
exports.getActiveCheckins = async (req, res) => {
    try {
        const [rows] = await db.query(`
            SELECT
                c.checkin_id,
                r.room_number,
                g.name AS guest_name,
                g.id_card
            FROM Checkins c
                     JOIN Rooms r ON c.room_id = r.room_id
                     JOIN Guests g ON c.guest_id = g.guest_id
            WHERE c.status = '入住中'
            ORDER BY r.room_number ASC
        `);
        res.status(200).json(rows);
    } catch (err) {
        console.error('获取入住中的记录错误:', err);
        res.status(500).json({ error: '获取入住中的记录失败', details: err.message });
    }
};

// Get a single check-in record by checkin_id (如果 api.js 中有路由 /admin/checkins/:id)
exports.getCheckinById = async (req, res) => {
    try {
        const { id } = req.params;
        const [rows] = await db.query(`
            SELECT
                c.checkin_id,
                c.guest_id,
                g.name AS guest_name,
                g.id_card AS guest_id_card,
                c.room_id,
                r.room_number,
                r.room_type,
                r.beds,
                r.price,
                c.checkin_date,
                c.checkout_date,
                c.total_amount,
                c.status
            FROM Checkins c
                     JOIN Guests g ON c.guest_id = g.guest_id
                     JOIN Rooms r ON c.room_id = r.room_id
            WHERE c.checkin_id = ?
        `, [id]);

        if (rows.length === 0) {
            return res.status(404).json({ error: '入住记录未找到。' });
        }
        res.status(200).json(rows[0]);
    } catch (err) {
        console.error('获取入住记录详情失败:', err);
        res.status(500).json({ error: '获取入住记录详情失败', details: err.message });
    }
};

// Get check-in records by guest ID card (客户端查询历史入住记录)
exports.getCheckinsByGuestCard = async (req, res) => {
    try {
        const { idCard } = req.params;
        const [rows] = await db.query(
            `SELECT
                 c.checkin_id,
                 r.room_number,
                 r.room_type,
                 r.price AS room_price,
                 c.checkin_date,
                 c.checkout_date,
                 c.status,
                 c.total_amount
             FROM Checkins c
             JOIN Guests g ON c.guest_id = g.guest_id
             JOIN Rooms r ON c.room_id = r.room_id
             WHERE g.id_card = ?
             ORDER BY c.checkin_date DESC`,
            [idCard]
        );
        res.status(200).json(rows);
    } catch (err) {
        console.error('根据身份证查询入住记录错误:', err);
        res.status(500).json({ error: '获取入住记录失败', details: err.message });
    }
};